<script setup>
import { onMounted, onUnmounted } from 'vue';
import { ref} from 'vue';
import { jwtDecode } from 'jwt-decode';
import http from './http';


// 模拟从localStorage获取token和过期时间的函数
function getTokenInfo() {
  const token = localStorage.getItem('token') || null;
  const retoken = localStorage.getItem('retoken') || null;
  return { token, retoken };
}

async function checkAndRefreshToken() {
  const { token, retoken } = getTokenInfo();

  if (token && retoken) {
    const decoded = jwtDecode(token);
    const exp = decoded.exp * 1000; // 将过期时间转换为毫秒
    console.log(exp);
    const timeLeft = exp - Date.now();
    console.log(timeLeft);

    if (timeLeft < 3600000) { // 如果剩余时间小于1小时
      confirm('Token即将过期，是否刷新？');
      const repsonse = await http.post('/rbac/retoken/', 
        {
          "retoken": retoken,
        }
      );
      if (repsonse.status === 200) {
        localStorage.setItem('token', repsonse.data.token);
      }
      else {
        console.log('刷新失败');
      }
    }
  }
}

let timerId = null;

// onMounted(() => {
//   if (timerId) {
//     clearInterval(timerId);
//   }
//    timerId = setInterval(checkAndRefreshToken, 1800000); // 每小时检查一次  
// });

// // 清理定时器
// onUnmounted(() => {
//   clearInterval(timerId);

// });






</script>

<template>

<router-view />

</template>

<style scoped>

</style>
